import React, { useEffect, useState } from "react";
import { deleteList, getList, postList } from "../../service";
import { ListState } from "../../types";
import {
  Table,
  Button,
  Space,
  Modal,
  Col,
  Row,
  Input,
  message as antdMessage,
} from "antd";
import { useSelector } from "react-redux";
import { RootState } from "../../store";
import { usePrimission } from "../../hooks/usePrimission";
import "./style.scss";
const Primisstion: React.FC<{ roles: string[]; children: JSX.Element }> = ({
  roles,
  children,
}) => {
  const role = useSelector((state: RootState) => state.user.role);
  if (role === "admin") return children;
  if (roles.includes(role)) return children;
  return null;
};
const Index: React.FC = () => {
  const [list, setList] = useState<ListState[]>([]);
  const role = useSelector((state: RootState) => state.user.role);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const adminPri = usePrimission(["admin"]);
  const testPri = usePrimission(["admin", "test", "user"]);
  const userPri = usePrimission(["admin", "user"]);
  const [keys, setKeys] = useState<React.Key[]>([]);
  const [item, setItem] = useState<ListState>({} as ListState);
  const [type, setType] = useState("全部");
  const [desc, setDesc] = useState("默认");
  const [searchValue, setSearchValue] = useState("");
  const columns = [
    {
      key: "id",
      title: "ID",
      dataIndex: "id",
    },
    {
      key: "title",
      title: "标题",
      dataIndex: "title",
    },
    {
      key: "price",
      title: "总价",
      dataIndex: "price",
    },
    {
      key: "type",
      title: "类型",
      dataIndex: "type",
    },
    {
      key: "image",
      title: "图片",
      dataIndex: "image",
      render(_: string) {
        return <img src={_} height={40}></img>;
      },
    },
    {
      key: "opration",
      title: "操作",
      render(_: ListState) {
        return (
          <Space>
            <Primisstion roles={["admin", "test", "user", "teacher"]}>
              <Button type="primary">添加</Button>
            </Primisstion>
            <Primisstion roles={["admin", "test"]}>
              <Button type="primary" danger onClick={() => handleDelete(_.id)}>
                删除
              </Button>
            </Primisstion>
            <Primisstion roles={["admin"]}>
              <Button type="primary" onClick={() => handleEdit(_)}>
                编辑
              </Button>
            </Primisstion>
          </Space>
        );
      },
    },
  ];
  const handleDelete = (id: string) => {
    Modal.confirm({
      title: "警告",
      content: "确认要删除吗？",
      okText: "确认删除",
      cancelText: "取消删除",
      async onOk() {
        await deleteList(id);
        await fetchData();
      },
    });
  };
  const handleEdit = (_: ListState) => {
    setIsModalOpen(true);
    setItem(_);
  };
  const fetchData = async () => {
    const resp = await getList({ type, desc, searchValue });
    setList(resp.data.data);
  };
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = async () => {
    const resp = await postList(item);
    const { code, message } = resp.data;
    if (code === 200) {
      antdMessage.success(message);
      await fetchData();
    }
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  useEffect(() => {
    fetchData();
  }, [type, desc, searchValue]);
  return (
    <div>
      <Row className="edit-item">
        <Col span={2}>搜索:</Col>
        <Col span={20}>
          <Input.Search
            defaultValue={searchValue}
            enterButton="Search"
            onSearch={value => setSearchValue(value)}
          ></Input.Search>
        </Col>
      </Row>
      <Row className="edit-item">
        <Col span={2}>类型:</Col>
        <Col span={20}>
          <Space>
            {["全部", "待付款", "已付款", "已发货", "已收货", "已完成"].map(
              (v, i) => {
                return (
                  <Button
                    key={i}
                    onClick={() => setType(v)}
                    type={type === v ? "primary" : "default"}
                  >
                    {v}
                  </Button>
                );
              }
            )}
          </Space>
        </Col>
      </Row>
      <Row className="edit-item">
        <Col span={2}>排序:</Col>
        <Col span={20}>
          <Space>
            {["默认", "升序", "降序"].map((v, i) => {
              return (
                <Button
                  key={i}
                  onClick={() => setDesc(v)}
                  type={desc === v ? "primary" : "default"}
                >
                  {v}
                </Button>
              );
            })}
          </Space>
        </Col>
      </Row>
      <Button type="primary" danger onClick={() => handleDelete(keys.join())}>
        选中删除
      </Button>
      <Table
        rowSelection={{
          onChange(keys) {
            setKeys(keys);
          },
        }}
        dataSource={list}
        columns={columns}
        rowKey="id"
      ></Table>

      <Modal
        title="编辑"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Row className="edit-item">
          <Col span={2}>ID:</Col>
          <Col span={22}>
            <Input
              disabled
              value={item.id}
              onChange={e => setItem({ ...item, id: e.target.value })}
            ></Input>
          </Col>
        </Row>
        <Row className="edit-item">
          <Col span={2}>标题:</Col>
          <Col span={22}>
            <Input
              value={item.title}
              onChange={e => setItem({ ...item, title: e.target.value })}
            ></Input>
          </Col>
        </Row>
        <Row className="edit-item">
          <Col span={2}>总价:</Col>
          <Col span={22}>
            <Input
              value={item.price}
              onChange={e => setItem({ ...item, price: +e.target.value })}
            ></Input>
          </Col>
        </Row>
        <Row className="edit-item">
          <Col span={2}>类型:</Col>
          <Col span={22}>
            <Input
              value={item.type}
              onChange={e => setItem({ ...item, type: e.target.value })}
            ></Input>
          </Col>
        </Row>
      </Modal>
    </div>
  );
};
export default Index;
